package com.funsport.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.entity.Notification;
import com.funsport.entity.User;
import com.funsport.mapper.NotificationMapper;
import com.funsport.mapper.UserMapper;
import com.funsport.util.WeChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 通知服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationService {
    
    private final NotificationMapper notificationMapper;
    private final UserMapper userMapper;
    private final WeChatUtil weChatUtil;
    
    /**
     * 发送通知
     */
    public void sendNotification(Long userId, String type, String title, String content, Map<String, String> data) {
        // 1. 保存通知到数据库
        Notification notification = new Notification();
        notification.setUserId(userId);
        // Note: Notification entity should have a type field
        // notification.setType(type);
        notification.setTitle(title);
        notification.setContent(content);
        notification.setIsRead(false);
        notification.setCreatedAt(LocalDateTime.now());
        
        notificationMapper.insert(notification);
        log.info("保存通知成功: userId={}, type={}, title={}", userId, type, title);
        
        // 2. 尝试发送微信模板消息
        try {
            User user = userMapper.selectById(userId);
            if (user != null && user.getOpenid() != null) {
                sendWeChatTemplateMessage(user.getOpenid(), type, title, content, data);
            }
        } catch (Exception e) {
            log.error("发送微信模板消息失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 发送活动提醒
     */
    public void sendEventReminder(Long userId, Long eventId, String eventName, LocalDateTime eventTime) {
        String title = "活动提醒";
        String content = String.format("您报名的活动「%s」即将在 %s 开始，请准时参加！", 
            eventName, eventTime.toString());
        
        Map<String, String> data = new HashMap<>();
        data.put("eventId", eventId.toString());
        data.put("eventName", eventName);
        data.put("eventTime", eventTime.toString());
        
        sendNotification(userId, "event_reminder", title, content, data);
    }
    
    /**
     * 发送预订提醒
     */
    public void sendBookingReminder(Long userId, Long bookingId, String venueName, LocalDateTime bookingTime) {
        String title = "预订提醒";
        String content = String.format("您预订的场地「%s」将在 %s 开始，请准时到达！", 
            venueName, bookingTime.toString());
        
        Map<String, String> data = new HashMap<>();
        data.put("bookingId", bookingId.toString());
        data.put("venueName", venueName);
        data.put("bookingTime", bookingTime.toString());
        
        sendNotification(userId, "booking_reminder", title, content, data);
    }
    
    /**
     * 发送积分变动通知
     */
    public void sendPointsNotification(Long userId, Integer points, String reason) {
        String title = points > 0 ? "积分到账" : "积分消耗";
        String content = String.format("您的积分%s %d 分，原因：%s", 
            points > 0 ? "增加了" : "减少了", Math.abs(points), reason);
        
        Map<String, String> data = new HashMap<>();
        data.put("points", points.toString());
        data.put("reason", reason);
        
        sendNotification(userId, "points_change", title, content, data);
    }
    
    /**
     * 获取用户通知列表
     */
    public Page<Notification> getUserNotifications(Long userId, Integer page, Integer pageSize, Boolean isRead) {
        LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Notification::getUserId, userId);
        
        if (isRead != null) {
            wrapper.eq(Notification::getIsRead, isRead);
        }
        
        wrapper.orderByDesc(Notification::getCreatedAt);
        
        return notificationMapper.selectPage(new Page<>(page, pageSize), wrapper);
    }
    
    /**
     * 标记为已读
     */
    public void markAsRead(Long notificationId, Long userId) {
        Notification notification = notificationMapper.selectById(notificationId);
        if (notification == null) {
            throw new RuntimeException("通知不存在");
        }
        
        if (!notification.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此通知");
        }
        
        notification.setIsRead(true);
        notificationMapper.updateById(notification);
        log.info("标记通知已读: id={}", notificationId);
    }
    
    /**
     * 标记全部已读
     */
    public void markAllAsRead(Long userId) {
        LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Notification::getUserId, userId)
               .eq(Notification::getIsRead, false);
        
        Notification update = new Notification();
        update.setIsRead(true);
        notificationMapper.update(update, wrapper);
        log.info("标记全部通知已读: userId={}", userId);
    }
    
    /**
     * 发送微信模板消息
     */
    private void sendWeChatTemplateMessage(String openid, String type, String title, String content, Map<String, String> data) {
        try {
            // 构建模板消息数据
            Map<String, Object> templateData = new HashMap<>();
            
            Map<String, Object> firstData = new HashMap<>();
            firstData.put("value", title);
            firstData.put("color", "#173177");
            templateData.put("first", firstData);
            
            Map<String, Object> keyword1Data = new HashMap<>();
            keyword1Data.put("value", content);
            keyword1Data.put("color", "#173177");
            templateData.put("keyword1", keyword1Data);
            
            Map<String, Object> keyword2Data = new HashMap<>();
            keyword2Data.put("value", LocalDateTime.now().toString());
            keyword2Data.put("color", "#173177");
            templateData.put("keyword2", keyword2Data);
            
            Map<String, Object> remarkData = new HashMap<>();
            remarkData.put("value", "点击查看详情");
            remarkData.put("color", "#173177");
            templateData.put("remark", remarkData);
            
            // 根据类型选择模板ID（需要在微信公众平台配置）
            String templateId = getTemplateId(type);
            
            if (templateId != null && !templateId.isEmpty()) {
                // weChatUtil.sendTemplateMessage(openid, templateId, "/pages/notification/index", templateData);
                log.info("发送微信模板消息成功: openid={}, type={}", openid, type);
            } else {
                log.warn("未配置模板ID: type={}", type);
            }
        } catch (Exception e) {
            log.error("发送微信模板消息失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 获取模板ID
     */
    private String getTemplateId(String type) {
        // 实际项目中应该从配置文件读取
        // 这里返回空字符串，不影响系统运行
        return "";
    }
}

